const { searchRecord, searchItems, getItems } = require("../../utils/feishuAPI");

Page({
  // 页面变量
  data: {
    classGoal: '',
    organGoal: '',
    progress: 0,       // 进度条默认值
    activeTab: 'group', // 默认的选项卡
    questionList: [],   // 当前本组问题列表数据
    classQuestionList: [],   // 当前班级问题列表数据
    historyQuestionList: [],   // 历史问题列表数据
  },
  
  onLoad: function () {
  },
  onShow: function () {
    console.log("current page: qa");

    // 页面显示时更新标题
    const app = getApp();
    app.updateTitle();
    app.updateGoal();
    console.log(app.globalData.classGoal)
    console.log(app.globalData.organGoal)
    this.setData({
      classGoal: app.globalData.classGoal,
      organGoal: app.globalData.organGoal,
    })

    // 更新问题
    this.updateQuestion();

    this.setData({
      progress: app.globalData.progress
    })
  },

  updateQuestion: function() {
    const that = this
    if (this.data.activeTab === 'group') {
      that.updateCurrentGroupQuestion()
    } else if (that.data.activeTab === 'class') {
      that.updateCurrentClassQuestion()
    } else {
      that.updateHistoryQuestion()
    }
  },

  updateCurrentGroupQuestion: function() {
    const that = this
    const app = getApp()
    const query = {
      filter: {
        "conjunction": "and",
        "conditions": [
          {
            "field_name": '周次',
            "operator": "is",
            "value": [
              app.globalData.week
            ]
          },
          {
            "field_name": '组号',
            "operator": "is",
            "value": [
              app.globalData.classInfo['组号']
            ]
          }
        ]
      }
    };
    searchRecord('问题管理表', query)
    .then((res) => {
      r = getItems('问题管理表', res.data.data.items)
      if (r != 0) {

        console.log(`问题：${r}`)
        console.log(r)
        qlist = []
        for (let i = 0; i < r.length; i++) {
          q = {
            title: '',
            content: '',
            tags: [],
            done: '未完成'
          }
          q['title'] = r[i]['问题']
          q['content'] = r[i]['答案']
          q['tags'] = r[i]['标签']
          q['done'] = r[i]['是否完成']
          console.log(q['tags'])
          qlist[i] = q
        }
        that.data.questionList = qlist
        that.setData({
          questionList: qlist
        })
      } else {
        console.log('update group question failed')
      }
    })
  },
  
  updateCurrentClassQuestion: function() {
    const that = this
    const app = getApp()
    const query = {
      filter: {
        "conjunction": "and",
        "conditions": [
          {
            "field_name": '周次',
            "operator": "is",
            "value": [
              app.globalData.week
            ]
          }
        ]
      }
    };
    searchRecord('问题管理表', query)
    .then((r) => {
      res = getItems('问题管理表', r.data.data.items)
      if (res != 0) {

        console.log(`问题：${res}`)
        console.log(res)
        qlist = []
        for (let i = 0; i < res.length; i++) {
          q = {
            title: '',
            content: '',
            tags: [],
            done: '未完成'
          }
          q['title'] = res[i]['问题']
          q['content'] = res[i]['答案']
          q['tags'] = res[i]['标签']
          q['done'] = res[i]['是否完成']
          qlist[i] = q
        }
        that.data.classQuestionList = qlist
        that.setData({
          classQuestionList: qlist
        })
      } else {
        console.log('update class question failed')
      }
    })
  },
  
  updateHistoryQuestion: function() {
    const that = this
    const app = getApp()
    const query = {
      filter: {
        "conjunction": "and",
        "conditions": [
          {
            "field_name": '周次',
            "operator": "isLessEqual",
            "value": [
              app.globalData.week
            ]
          }
        ]
      }
    };
    searchRecord('问题管理表', query)
    .then((r) => {
      res = getItems('问题管理表', r.data.data.items)
      if (res != 0) {

        console.log(`问题：${res}`)
        console.log(res)
        qlist = []
        for (let i = 0; i < res.length; i++) {
          q = {
            title: '',
            content: '',
            tags: [],
            done: '未完成'
          }
          q['title'] = res[i]['问题']
          q['content'] = res[i]['答案']
          q['tags'] = res[i]['标签']
          q['done'] = res[i]['是否完成']
          qlist[i] = q
        }
        that.data.historyQuestionList = qlist
        that.setData({
          historyQuestionList: qlist
        })
      } else {
        console.log('update history question failed')
      }
    })
  },

  // 切换目标（课程目标/组织目标）
  switchGoal(e) {
    const goal = e.currentTarget.dataset.goal; // 获取点击的目标类型
    if (goal === 'class') {
      this.setData({ classGoalActive: true });
    } else {
      this.setData({ classGoalActive: false });
    }
  },

  // 切换选项卡
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab; // 获取点击的选项卡
    this.setData({ activeTab: tab }); // 更新活动选项卡
    this.updateQuestion()
  },

  
  // 跳转到详情页
  navigateToDetail(e) {
    const index = e.currentTarget.dataset.index; // 获取点击的卡片索引
    const question = this.data.questionList[index];
    tt.navigateTo({
      url: `../qaDetail/qaDetail?question=currentCard`,
      success: function(res){
         // 传递数据到详情页
          tt.setStorage({
            key: 'currentCard',
            data: question
          })
      },
    });
  },

  // 发起新内容
  createNewContent() {
    console.log('点击发布问题按钮')
    tt.navigateTo({
      // url: '../post/post'
      url: `/pages/view/view?url=${encodeURIComponent(`https://byd3anf1gt.feishu.cn/share/base/form/shrcnCd8hITPPmqZvnXHu0eH8ph`)}`
    });
  },

  // 更新进度条值
  updateProgress(newProgress) {
    // 传入一个新的进度值，更新数据绑定
    this.setData({ progress: newProgress });
  },
});